<template>
    <el-container>
       <el-aside >
         <el-header>
           <el-button-group>
            <el-button size="mini" icon="el-icon-plus" @click="addCtrl">添加组织</el-button>
            <el-button size="mini" icon="el-icon-edit" @click="editCtrl">编辑组织</el-button>
            <el-button size="mini" icon="el-icon-upload"  @click="uploadCtrl">导入组织</el-button>
            <el-button size="mini" icon="el-icon-close" @click="deleteCtrl" style='color:red'>删除组织</el-button>
          </el-button-group>
          <el-input
            size="small"
            placeholder="请输入内容"
            suffix-icon="el-icon-search"
            v-model="orgSerch">
          </el-input>
         </el-header>

        <el-tree
        :props="props"
        :load="loadNode"
        ref="tree"
        lazy
        @node-click='getNode'
        node-key="id"
        >
      </el-tree>
    </el-aside>    
    <el-main>
      <orgDtl :orgId.sync='orgId' :sonInvi='sonNum_inviteCode'></orgDtl>  
    </el-main>
    <!-- 增加、编辑的弹框 -->
    <el-dialog 
    :title="dialogTittle" 
    :visible.sync="dialogFormVisible"
    @close='closeDialog'
    >
        <el-form :model="form">
          <el-form-item label="上级组织" :label-width="formLabelWidth">
            <!-- <el-input size="mini" v-model="form.pName" auto-complete="off" placeholder="请输入上级组织名称"> -->
            <!-- </el-input> -->
            <el-autocomplete
                size="mini"
                v-model="form.pName"
                :fetch-suggestions="querySearchAsync"
                placeholder="请输入上级组织名称"
                @select="handleSelect"
                :trigger-on-focus="false"
                value-key="name"
                :disabled="canBeSelect ? true : false"
              ></el-autocomplete>
          </el-form-item>
          <el-form-item label="组织名称" :label-width="formLabelWidth">
            <el-input size="mini" v-model="form.name" auto-complete="off" placeholder="请输入组织名称（限28字）"></el-input>
            <span class="errTips">{{errTips}}</span>
          </el-form-item>
          <el-form-item label="组织坐标" :label-width="formLabelWidth">
            <el-input size="mini" style="width:70%;margin-right:20px" v-model="form.lonLat" auto-complete="off" placeholder="请输入组织坐标（选填）"></el-input>
            <el-button size="mini" style="padding:7px 15px" type="danger" >拾取</el-button>
          </el-form-item>

          <el-form-item  style="overflow:hidden">
              <el-form-item style="width:50%;float:left" label="组织地址" :label-width="formLabelWidth">
                <el-input size="mini" v-model="form.address" auto-complete="off" placeholder="请输入组织地址（选填）"></el-input>
              </el-form-item>
              <el-form-item style="width:50%;float:left" label="联系方式" :label-width="formLabelWidth">
                <el-input size="mini" v-model="form.tel" auto-complete="off" placeholder="请输入组织联系方式（选填）"></el-input>
              </el-form-item>
          </el-form-item>
          

          <el-form-item label="组织介绍" :label-width="formLabelWidth"> 
              <el-input placeholder="请输入组织介绍（限200字）" type="textarea" v-model="form.content"></el-input>
            </el-form-item>
                    
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button style="padding:9px 15px" @click="dialogCancle">取 消</el-button>
          <el-button style="padding:9px 15px" type="primary" @click="dialogSureBtn">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 删除提示 -->
      <el-dialog
        title="删除组织"
        :visible.sync="deleteOgr"
        width="30%"
        >
        <span>确认删除该组织吗？</span>
        <span slot="footer" class="dialog-footer">
          <el-button style="padding:9px 15px" @click="deleteOgr = false">取 消</el-button>
          <el-button style="padding:9px 15px" type="primary" @click="deleteSure">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 导入文件的组件-->
      <fileuploadDialog 
       :showUploadDialog='showUploadDialog'
       :importUrl="importUrl"
       v-on:listUploadFile="getFlie" 
       v-on:closeGetFlieDialog='closeGetFlieDialog'></fileuploadDialog>

    </el-container>  
</template>

<script>
import {findSonList,doSave,delOrg,getOrgDtl,findOrgList,findOrg,orgBatchImport} from '../../tool/config'
import orgDtl from './orgDtl'
import { Notification } from 'element-ui'
import fileuploadDialog from '../common/fileuploadDialog.vue'
  export default {
    components:{orgDtl,fileuploadDialog},
    data() {
      return {
        props: {
          label: 'name',
          children: 'zones'
        },
        count: 1,
        orgSerch:'',
        orgId:'',//被选中的组织树
        sonNum_inviteCode:{},//需要传递的组织数和邀请码
        selData:'',//被选中的node
        //弹框
        dialogFormVisible: false,//编辑和添加的弹框
        showUploadDialog:false,//文件上传弹框
        deleteOgr:false,//删除的弹框
        formLabelWidth: '100px',
        errTips:'',
        form: {
          name: '',
          content: '',
          pName:'',//当前父级名称
          tel:'',
          lonLat:'',
          address:'',
          pid:'',
          id:'',
          key:0
        },
        dialogTittle:'',//编辑和增加的弹框标题
        parentKey:'',//父key
        restaurants: [],//上级组织
        canBeSelect:false,
        importUrl:''//文件导入路径
      };
    },
    mounted(){
      this.importUrl = orgBatchImport();
    },
    methods: {
      getNode(data,node) {
        // 获取父组织名称和id
        if(node.parent.data){
          this.form.pName = node.parent.data.name;
        }else{
          this.form.pName = '';
        }
        this.parentKey = node.parent.key;
        this.form.key = node.key;
        this.form.pid = data.pid + '';
        this.selData = node;
        this.orgId = data.id + '';
        this.pid = data.pid + '';
        this.sonNum_inviteCode.sonNum = data.sonNum;
        this.sonNum_inviteCode.inviteCode = data.inviteCode;
        this.sonNum_inviteCode.name = data.name;
      },
      //获取文件dialog关闭后的值
      getFlie(value,dialogFile){
        this.showUploadDialog = false;
      },
      handleNodeClick(data) {
        console.log(data);
      },
      getList(id,callback){//组织树
        findSonList({id:id}).then((res)=>{
        if(res.code == 0){
          return callback(res.response)
        }
       })
      },
      getOrgTree(callback){
        findOrg().then((res)=>{
          console.log(res)
          if(res.response){
            return callback(res.response)
          }else{
            return callback([])
          }
        })
      },
      getOrgMsg(id,callback){//当前组织信息
        getOrgDtl({id:id}).then((res)=>{
            callback(res)
        })
      },
      findOrg(name,callback){//搜索组织
        findOrgList({name:name}).then((res)=>{
          callback(res)
        })
      },
      deleteCtrl(){
        if(!this.orgId){
        this.$notify({
          title: '提示',
          message: '请选择一条组织',
          duration: 3000,
          type: 'warning'
        });
        }else{
          this.deleteOgr = true;
        }
      },
      deleteSure(){
        this.deleteOgr = false;
         delOrg({id:this.orgId}).then((res)=>{
           if(res.code == 0){
            this.$refs.tree.remove(this.selData);//删除此节点
           }
           this.$notify({
              title: '提示',
              message: res.msg,
              duration: 3000,
              type: 'warning'
            });
         })
      },
      editCtrl(){
        if(!this.orgId){
          this.$notify({
            title: '提示',
            message: '请选择一条组织',
            duration: 3000,
            type: 'warning'
          });
        }else{
            this.dialogTittle = '编辑组织';
            this.dialogFormVisible = true;
            this.getOrgMsg(this.orgId,(res)=>{
              console.log(res)
            if(res.code == 0){
              this.form.name = res.response.name || '';
              this.form.content = res.response.content || '';
              this.form.lonLat = res.response.lon + res.response.lon || '';
              this.form.address = res.response.address || '';
              this.form.tel = res.response.tel || '';
            }
          })
        }
        
      },
      editCtrlServe(){
        this.form.id = this.orgId;
        var obj ={
          content: this.form.content,
          tel:this.form.tel,
          lonLat:this.form.lonLat,
          address:this.form.address,
          pid:this.form.pName == ''? '' : this.form.pid,
          id:this.form.id,
          name:this.form.name
        }
        doSave(obj).then((res)=>{
          if(res.code == 0){
            //更改树节点
            var key;
            // if(!this.parentKey){
              // key = this.orgId;
              // console.log(this.selData)
              // this.$refs.tree.insertAfter(res.response,this.orgId);
              // this.$refs.tree.remove(this.selData);
            // }else{
              key = this.parentKey;
              this.$refs.tree.append(res.response,key);
              this.$refs.tree.remove(this.selData);
            // }
            
            this.dialogFormVisible = false;
            this.$notify({
              title: '提示',
              message: '修改成功',
              duration: 3000,
              type: 'success'
            })
          }else{
            this.errTips = res.msg;
          }
        })
      },
      //添加组织
      addCtrl(){
        this.dialogTittle = '添加组织';
        this.dialogFormVisible = true;
      },
      addCtrlServe(){
        var obj ={
          content: this.form.content,
          tel:this.form.tel,
          lonLat:this.form.lonLat,
          address:this.form.address,
          pid:this.form.pid,
          name:this.form.name
        }
        doSave(obj).then((res)=>{
          if(res.code == 0){
            //新增
            this.$refs.tree.append(res.response,this.form.pid);
            this.dialogFormVisible = false;
            this.$notify({
              title: '提示',
              message: '添加成功',
              duration: 3000,
              type: 'success'
            })
          }else{
            this.errTips = res.msg;
          }
        })
      },

      dialogSureBtn(){
        if(this.form.name == ''){
          this.errTips = '组织名称不能为空';
          return
        }else{
           this.errTips = '';
        }
        
        if(this.dialogTittle == '编辑组织'){
          this.editCtrlServe()
        }
        if(this.dialogTittle == '添加组织'){
          this.addCtrlServe()
        }
        
      },
      dialogCancle(){
        //关闭弹幕框时
        this.dialogFormVisible = false;
      },
      closeDialog(){
          this.errTips = '';
      },
      uploadCtrl(){
        this.showUploadDialog = true;
      },
      closeGetFlieDialog(val){
        this.showUploadDialog = val;
      },
      // 上级组织输入框选择
      querySearchAsync(queryString, cb) {
        //返回可选列表
          cb(this.restaurants);
      },
      handleSelect(item) {
        // 获取父id
        this.form.pid = item.id + '';
      },
      loadNode(node, resolve) {
        //一级菜单 需要调管理员权限
        this.getOrgTree((list)=>{
            if (node.level === 0) {
              return resolve(list);
          }
        
        //当前层级是否有子级
        var hasChild = node.data.sonNum;
        var data;
            if (hasChild > 0) {
              this.getList(node.data.id,(res)=>{
                data = res;
                resolve(data);
              })
            } else {
              data = [];
              resolve(data);
            }
        })

      },
      
      
  },
  computed: {
      pName() {
      　　　　return this.form.pName
  　　},
  },
  watch: {
        pName(newValue, oldValue) {
            if(newValue != oldValue){
              this.findOrg(newValue,(res)=>{
                this.restaurants = res.response;
              })
            }
    　　},
        dialogTittle(newValue,oldValue){
          if(newValue == '编辑组织'){
           this.canBeSelect = true;
          }
          if(newValue == '添加组织'){
            this.canBeSelect = false;
          }
        }
     }
}
</script>

<style scoped>
.el-header{
  padding: 0;
  margin-bottom: 20px;
}
.el-button{
  padding-left: 4px;
  padding-right: 4px;
}
.el-button-group{
  margin-bottom: 20px;
}
.el-tree{
  max-height: 100%;
  overflow: auto;
}
.el-main{
  padding:0 0 20px 20px;
}
#tab-first{
  line-height: 0px;
}
.el-table td, .el-table th{
  padding: 5px 0;
}
.errTips{
  color:red;
  font-size:12px;
  position:absolute;
  line-height:14px;
  margin-top:2px;
}
</style>